const Fn = require('./fn.js')
const Acan = require('../lib/Acan')
// const test = createTable('tt.test', {
//   name: { len: 10, type: 'string', encoding: 'utf8'},
//   uptime: { type: 'double'},
//   test: { len: 20, type: 'string', encoding: 'utf8'},
//   rand: { len: 20, type: 'string', encoding: 'utf8'},
//   bool: { type: 'bool', default: false },
//   int: { len: 2, type: 'int' }, // int len: 1-6, 1: 128, 2: 128 * 256, 3: 128 * 256 * 256
//   time: { type: 'time' },
//   date: { len: 20, type: 'string', encoding: 'utf8'}
// }, { update: true })

const test = tables['tt.test']
Adebug.log('creatTable test')

const errFn = (e) => {
  if (e.code === 'ECONNREFUSED') return // console.log(e)
  console.log(e)
}

let geti = 0
let upLen = 0
let upLastLen = 0
let getLen = 0
let getLast = 0
let getLastLen = 0
setInterval(() => {
  console.log('qps:', geti - getLast, 'down:', ((getLen - getLastLen) / 1024).toFixed(2), 'kb/s', 'up:', ((upLen - upLastLen) / 1024).toFixed(2), 'kb/s')
  getLast = geti
  getLastLen = getLen
  upLastLen = upLen
}, 1000)
const httpGet = (url, obj) => {
  const req = http.request(url + '?' + Acan.url.unite(obj), { agent }, (res) => {
    geti++
    if (res.statusCode === 200) return
    // console.log(res.statusCode)
  })
  req.on('error', errFn)
  req.end()
  return req
}
const httpPost = (url, obj, post) => {
  const req = http.request(url + '?' + Acan.url.unite(obj), { method: 'POST', agent, headers: {"Connection":"Keep-Alive"} }, (res) => {
    geti++
    if (res.statusCode === 200) return
    res.setEncoding('utf8')
    res.on('data', (data) => {
      console.log(JSON.parse(data))
    })
  })
  req.on('error', errFn)
  req.end(JSON.stringify(post))
  return req
}

const nrr = ['test', 'test', 'haha', 'hehe', 'hello']
const loop = async(times) => {
  console.log('Start Create')
  let ti = 0
  while(true) {
    await sleep(10)
    if (times && ti >= times) return console.log('插入完成')
    const rand = 800
    const data = {
      name: nrr[Acan.random(0, nrr.length - 1)],
      uptime: process.uptime(),
      test: Acan.random(1000, 9999).toString(32) + '-' + ti,
      rand: '-' + Acan.random(0, 1699999999),
      bool: !!Acan.random(0, 1),
      int: Acan.random(0, 99),
      time: Acan.time(),
      date: Acan.time('Y-m-d H:i:s')
    }
    for (let i = 0; i < rand; i++) {
      test.create(data)
      geti++
    }
    ti++
  }
}

const loopFind = async(c) => {
  console.log('Start Find')
  let ti = 0
  while(true) {
    await sleep(20)
    // const rand = Acan.random(5, 50)
    const rand = 100
    for (let i = 0; i < rand; i++) {
      test.find({})
      geti++
    }
  }
}

const pool = () => {
  // loop()
  loopFind()
}
pool()
// pool()
